#include "Drv_Param.h"

static uint32_t GetPage(uint32_t addr)
{
    uint32_t page = 0;
    page = RT_ALIGN_DOWN(addr, FLASH_PAGE_SIZE);
    return page;
}


int flash_read(uint32_t addr, uint8_t *buf, uint32_t size)
{
    uint32_t i;

    if ((addr + size) > STM32_FLASH_END_ADDRESS)
    {
        
        return -1;
    }

    for (i = 0; i < size; i++, buf++, addr++)
    {
        *buf = *(uint8_t *) addr;
    }

    return size;
}

int flash_write(uint32_t addr, const uint8_t *buf, uint32_t size)
{
    int result = 0;
    uint32_t end_addr   = addr + size;


    if ((end_addr) > STM32_FLASH_END_ADDRESS)
    {
       
        return -1;
    }

    FLASH_Unlock();
//*     @arg FLASH_FLAG_PGERR: FLASH Program error flag       
//*     @arg FLASH_FLAG_WRPRTERR: FLASH Write protected error flag      
//*     @arg FLASH_FLAG_EOP: FLASH End of Operation flag     
    FLASH_ClearFlag(FLASH_FLAG_PGERR|FLASH_FLAG_WRPRTERR|FLASH_FLAG_EOP);
    FLASH_ErasePage(GetPage(addr));
    while (addr < end_addr)
    {
        if (FLASH_ProgramOptionByteData(addr, *((uint8_t *)buf)) == FLASH_COMPLETE)
        {
            if (*(uint8_t *)addr != *(uint8_t *)buf)
            {
                result = -1;
                break;
            }
            addr += 1;
            buf  += 1;
        }
        else
        {
            result = -1;
            break;
        }
    }

    FLASH_Lock();

    if (result != 0)
    {
        return result;
    }

    return size;
}
